from django.db import models

# Create your models here.

from django.contrib.auth.models import AbstractUser

# 产品设计必须保存的字段有      用户名，密码，手机
# 选择的是abstractuser     它只有用户名，密码，邮箱
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData

from mall import settings


class User(AbstractUser):
    # 用户模型类
    mobile = models.CharField(max_length=11, unique=True, verbose_name='手机号')
    email_active = models.BooleanField(default=False, verbose_name='邮箱验证状态')

    class Meta:
        # 配置相关信息
        db_table = 'tb_users'  # 指明数据库表明
        verbose_name = '用户'  # admin站点中显示的名称
        verbose_name_plural = verbose_name  # 显示的复数名称

    def generic_verify_url(self):
        # 需要将id进行处理，同时生成一个url:http://xxxx?token=xxxx
        serializer = Serializer(settings.SECRET_KEY, 3600)
        # 为了查询更多准备，我们可以添加更多信息
        token = serializer.dumps({'id': self.id, 'email': self.email})

        return 'http://www.meiduo.site:8080/success_verify_email.html?token=' + token.decode()

    @staticmethod
    def generic_user_info(token):
        serializer = Serializer(settings.SECRET_KEY, 3600)
        try:
            result = serializer.loads(token)
        except BadData:
            return None
        else:
            # 我们根据id，查询用户信息，来返回用户信息
            id = result.get('id')
            email = result.get('email')
            # select * from user where id=xxx and email=xxxx
            # 只通过一个id也可以查询出用户信息,多加一个条件就是为了让查询更准确
            try:
                user = User.objects.get(id=id, email=email)
            except User.DoesNotExist:
                return None
            else:
                return user
